package com.haiheng.module_main.fragment.bookcar

import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.AppConstant.Companion.SP_USER_LOGIN
import com.haiheng.common.constant.RourePage
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.bookcar.BookCarListAdapter
import com.haiheng.module_main.databinding.FragmentBookCarScanBinding
import com.haiheng.module_main.dialog.ScanDialog
import com.haiheng.module_main.mode.BookCarScanViewModel
import com.haiheng.module_main.mode.BookCarShelfViewModel

/**
 *
 * @Des: 扫书页面
 * @Author: hwz
 * @Date:2024/8/16 0016
 * @Version: 1.0
 */

class BookCarScanFragment : RouterFragment(), ScanDialog.OnScanResultCallback {
    private lateinit var binding: FragmentBookCarScanBinding
    private val bookCarShelfViewModel: BookCarShelfViewModel by viewModels()

    private val viewModel: BookCarScanViewModel by viewModels()
    private val bookCarListAdapter = BookCarListAdapter()
    private lateinit var scanDialog: ScanDialog
    private lateinit var loadingDialog : LoadingDialog

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBookCarScanBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun initView() {
        var userlOgin = SPUtils.getInstance().getString(SP_USER_LOGIN)
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)

        binding.includeTile.tvTitle.setText("书车扫描")
        binding.includeTile.btnFinishScan.visibility = View.VISIBLE
        binding.includeTile.tvCarName.visibility = View.VISIBLE
        binding.includeTile.tvClear.visibility = View.GONE

        binding.includeTile.tvCarName.text = AppConstant.getCarName()
        binding.includeBottom.slBottomRight.visibility = View.GONE
        binding.includeBottom.tvBottomLeft.text = "扫描图书"
        binding?.rvList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvList?.adapter = bookCarListAdapter

        binding.includeBottom.slBottomLeft.setOnClickListener {
//            var intent = Intent(activity,ScanActivity::class.java)
//            startActivity(intent)
            showScanDialog()
        }
        binding.includeBottom.slBottomRight.setOnClickListener {

        }
        binding.includeTile.sflBack.setOnClickListener {
            activity.navigation(RourePage.BOOK_CAR_LOGIN_RESULT)
        }
        binding.ivClearBacode.setOnClickListener {
            binding.etBarCode.setText("")
        }
        binding.etBarCode.setInputType(InputType.TYPE_CLASS_TEXT);
        binding.etBarCode.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.etBarCode.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.queryBookDetail(binding.etBarCode.text.toString())
                // 处理搜索逻辑
                true
            } else false
        })
        binding.includeTile.btnFinishScan.setOnClickListener {
            if (viewModel.bookInfoList.value.isNullOrEmpty()){
                ToastUtils.showShort("清洗扫描书籍")
                return@setOnClickListener
            }
            loadingDialog.show()
            viewModel.finScan(bookCarListAdapter.getData())
        }

        bookCarListAdapter.setOnItemChildClickListener(object :BaseAdapter.OnItemChildClickListener{
            override fun onItemChildClick(
                view: View,
                holder: BaseAdapter.ViewBindHolder,
                position: Int
            ) {
                if (view.id == R.id.ivDelete){
                    viewModel.deleteBook(bookCarListAdapter.getItem(position))
                }
            }
        })
    }

    fun showScanDialog() {
        // 在需要显示Dialog的时候才进行初始化
        if (!::scanDialog.isInitialized) {
            scanDialog = ScanDialog(requireActivity(), this) // 使用requireActivity()更安全
        }
        scanDialog.show()
    }

    override fun initViewModel(): BaseViewModel? {
        viewModel.faiMsg.observe(viewLifecycleOwner){
            loadingDialog.hide()
            if ("扫描完成".equals(it)){
                viewModel._bookInfoList.postValue(emptyList())
//                activity.navigation(RourePage.BOOK_CAR_LOGIN_RESULT)
            }
            ToastUtils.showShort(it)
        }
        viewModel.bookInfoList.observe(viewLifecycleOwner) {
            bookCarListAdapter.setNewData(it)
            binding.tvBookTotalNum.setText("已扫描：${it.size}本")
        }
        bookCarShelfViewModel.bookInfoList.observe(viewLifecycleOwner){
            viewModel.addBookList(it)
        }
        bookCarShelfViewModel.faiMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort("$it")
        }
        return viewModel
    }

    override fun initLoad() {

        bookCarShelfViewModel.getBookList()
    }

    override fun onScanSuccess(result: String?) {
        binding.etBarCode.setText(result)
        viewModel.queryBookDetail(result)
    }

    override fun onScanError(error: String?) {

    }
}